//
//  CommentViewController.swift
//  Spookiness
//
//  Created by 腾億 on 2017/12/14.
//  Copyright © 2017年 tml. All rights reserved.
//

import UIKit

class CommentViewController: UIViewController {

    
    weak var delegate:ComicViewWillEndDraggingDelegate?
    var detailStatic: DetailStaticModel?
    var commentList: CommentListModel?
    
    fileprivate lazy var tableView:UITableView = {
       let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CommentCell.self, forCellReuseIdentifier: "CommentCell")
        tableView.tableFooterView = UIView()
        tableView.refreshFoot = RefreshBackNormalFooter {
            self.loadData()
        }
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(self.tableView)
        setUpSnap()
        // Do any additional setup after loading the view.
    }

    fileprivate func setUpSnap() {
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view.usnp.edges)
        }
    }
    
    func commentReloadData() {
        self.tableView.reloadData()
    }
    
    fileprivate func loadData() {
        NetworkTool.loadCommentData(object_id: detailStatic?.comic?.comic_id ?? 0, thread_id: detailStatic?.comic?.thread_id ?? 0, page: commentList?.serverNextPage ?? 0) {[weak self] (commentListModel) in
            if commentListModel.hasMore == true {
                self?.tableView.refreshFoot.endRefreshing()
            }else {
                self?.tableView.refreshFoot.endRefreshingWithNoMoreData()
            }
            for item in commentListModel.commentList {
                self?.commentList?.commentList.append(item)
            }
            self?.tableView.reloadData()
        }
    }

}

extension CommentViewController: UITableViewDelegate, UITableViewDataSource {
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        delegate?.comicWillEndDragging(scrollView)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commentList?.commentList.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
        cell.model = commentList?.commentList[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = commentList?.commentList[indexPath.row]
        return CommentCell.height(model)
    }
   
    
}




